JSON response parsing in Javascript to get key/value pair
Try the JSON Parser by Douglas Crockford at github.
You can then simply create a JSON object out of your String variable as shown below:
var JSONText = '{"c":{"a":[{"name":"cable - black","value":2},{"name":"case","value":2}]},"o":{"v":[{"name":"over the ear headphones - white/purple","value":1}]},"l":{"e":[{"name":"lens cleaner","value":1}]},"h":{"d":[{"name":"hdmi cable","value":1},{"name":"hdtv essentials (hdtv cable setup)","value":1},{"name":"hd dvd \u0026 blue-ray disc lens cleaner","value":1}]}'
var JSONObject = JSON.parse(JSONText);
var c = JSONObject["c"];
var o = JSONObject["o"];
How can I delete one element from an array by value
If you also want to make this deletion operation chainable, so you can delete some item and keep on chaining operations on the resulting array, use tap
:
[2, 4, 6, 3, 8].tap { |ary| ary.delete(3) }.count #=> 4
TypeScript Objects as Dictionary types as in C#
Lodash has a simple Dictionary implementation and has good TypeScript support
Install Lodash:
npm install lodash @types/lodash --save
Import and usage:
import { Dictionary } from "lodash";
let properties : Dictionary<string> = {
"key": "value"
}
console.log(properties["key"])
Creating stored procedure with declare and set variables
I assume you want to pass the Order ID in. So:
CREATE PROCEDURE [dbo].[Procedure_Name]
(
@OrderID INT
) AS
BEGIN
Declare @OrderItemID AS INT
DECLARE @AppointmentID AS INT
DECLARE @PurchaseOrderID AS INT
DECLARE @PurchaseOrderItemID AS INT
DECLARE @SalesOrderID AS INT
DECLARE @SalesOrderItemID AS INT
SET @OrderItemID = (SELECT OrderItemID FROM [OrderItem] WHERE OrderID = @OrderID)
SET @AppointmentID = (SELECT AppoinmentID FROM [Appointment] WHERE OrderID = @OrderID)
SET @PurchaseOrderID = (SELECT PurchaseOrderID FROM [PurchaseOrder] WHERE OrderID = @OrderID)
END
How do I remove duplicate items from an array in Perl?
Try this, seems the uniq function needs a sorted list to work properly.
use strict;
# Helper function to remove duplicates in a list.
sub uniq {
my %seen;
grep !$seen{$_}++, @_;
}
my @teststrings = ("one", "two", "three", "one");
my @filtered = uniq @teststrings;
print "uniq: @filtered\n";
my @sorted = sort @teststrings;
print "sort: @sorted\n";
my @sortedfiltered = uniq sort @teststrings;
print "uniq sort : @sortedfiltered\n";
Running multiple async tasks and waiting for them all to complete
There should be a more succinct solution than the accepted answer. It shouldn't take three steps to run multiple tasks simultaneously and get their results.
- Create tasks
- await Task.WhenAll(tasks)
- Get task results (e.g., task1.Result)
Here's a method that cuts this down to two steps:
public async Task<Tuple<T1, T2>> WhenAllGeneric<T1, T2>(Task<T1> task1, Task<T2> task2)
{
await Task.WhenAll(task1, task2);
return Tuple.Create(task1.Result, task2.Result);
}
You can use it like this:
var taskResults = await Task.WhenAll(DoWorkAsync(), DoMoreWorkAsync());
var DoWorkResult = taskResults.Result.Item1;
var DoMoreWorkResult = taskResults.Result.Item2;
This removes the need for the temporary task variables. The problem with using this is that while it works for two tasks, you'd need to update it for three tasks, or any other number of tasks. Also it doesn't work well if one of the tasks doesn't return anything. Really, the .Net library should provide something that can do this
How to make git mark a deleted and a new file as a file move?
Git will automatically detect the move/rename if your modification is not too severe. Just git add
the new file, and git rm
the old file. git status
will then show whether it has detected the rename.
additionally, for moves around directories, you may need to:
- cd to the top of that directory structure.
- Run
git add -A .
- Run
git status
to verify that the "new file" is now a "renamed" file
If git status still shows "new file" and not "renamed" you need to follow Hank Gay’s advice and do the move and modify in two separate commits.
Spring Security exclude url patterns in security annotation configurartion
When you say adding antMatchers doesnt help - what do you mean? antMatchers is exactly how you do it. Something like the following should work (obviously changing your URL appropriately):
@Override
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/authFailure").permitAll()
.antMatchers("/resources/**").permitAll()
.anyRequest().authenticated()
If you are still not having any joy, then you will need to provide more details/stacktrace etc.
Details of XML to Java config switch is here
Parsing HTML using Python
Here you can read more about different HTML parsers in Python and their performance. Even though the article is a bit dated it still gives you a good overview.
Python HTML parser performance
I'd recommend BeautifulSoup even though it isn't built in. Just because it's so easy to work with for those kinds of tasks. Eg:
import urllib2
from BeautifulSoup import BeautifulSoup
page = urllib2.urlopen('http://www.google.com/')
soup = BeautifulSoup(page)
x = soup.body.find('div', attrs={'class' : 'container'}).text
error: Unable to find vcvarsall.bat
I had the same error (which I find silly and not really helpful whatsoever as error messages go) and continued having problems, despite having a C compiler available.
Surprising, what ended up working for me was simply upgrading pip and setuptools to the most recent version. Hope this helps someone else out there.
Creating multiple objects with different names in a loop to store in an array list
You can use this code...
public class Main {
public static void main(String args[]) {
String[] names = {"First", "Second", "Third"};//You Can Add More Names
double[] amount = {20.0, 30.0, 40.0};//You Can Add More Amount
List<Customer> customers = new ArrayList<Customer>();
int i = 0;
while (i < names.length) {
customers.add(new Customer(names[i], amount[i]));
i++;
}
}
}
Force encode from US-ASCII to UTF-8 (iconv)
People say you can't and I understand you may be frustrated when asking a question and getting such an answer.
If you really want it to show in UTF-8 instead of US ASCII then you need to do it in two steps.
First:
iconv -f us-ascii -t utf-16 yourfile > youfileinutf16.*
Second:
iconv -f utf-16le -t utf-8 yourfileinutf16 > yourfileinutf8.*
Then if you do a file -i
, you'll see the new character set is UTF-8.
'"SDL.h" no such file or directory found' when compiling
If the header file is /usr/include/sdl/SDL.h
and your code has:
#include "SDL.h"
You need to either fix your code:
#include "sdl/SDL.h"
Or tell the preprocessor where to find include files:
CFLAGS = ... -I/usr/include/sdl ...
2D Euclidean vector rotations
Rotating a vector 90 degrees is particularily simple.
(x, y)
rotated 90 degrees around (0, 0)
is (-y, x)
.
If you want to rotate clockwise, you simply do it the other way around, getting (y, -x)
.
Word wrap for a label in Windows Forms
I had to find a quick solution, so I just used a TextBox with those properties:
var myLabel = new TextBox
{
Text = "xxx xxx xxx",
WordWrap = true,
AutoSize = false,
Enabled = false,
Size = new Size(60, 30),
BorderStyle = BorderStyle.None,
Multiline = true,
BackColor = container.BackColor
};
Why am I getting the error "connection refused" in Python? (Sockets)
This error means that for whatever reason the client cannot connect to the port on the computer running server script. This can be caused by few things, like lack of routing to the destination, but since you can ping the server, it should not be the case. The other reason might be that you have a firewall somewhere between your client and the server - it could be on server itself or on the client. Given your network addressing, I assume both server and client are on the same LAN, so there shouldn't be any router/firewall involved that could block the traffic. In this case, I'd try the following:
- check if you really have that port listening on the server (this should tell you if your code does what you think it should): based on your OS, but on linux you could do something like
netstat -ntulp
- check from the server, if you're accepting the connections to the server: again based on your OS, but
telnet LISTENING_IP LISTENING_PORT
should do the job
- check if you can access the port of the server from the client, but not using the code: just us the telnet (or appropriate command for your OS) from the client
and then let us know the findings.
How can I determine if a date is between two dates in Java?
Here you go:
public static void main(String[] args) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
String oeStartDateStr = "04/01/";
String oeEndDateStr = "11/14/";
Calendar cal = Calendar.getInstance();
Integer year = cal.get(Calendar.YEAR);
oeStartDateStr = oeStartDateStr.concat(year.toString());
oeEndDateStr = oeEndDateStr.concat(year.toString());
Date startDate = sdf.parse(oeStartDateStr);
Date endDate = sdf.parse(oeEndDateStr);
Date d = new Date();
String currDt = sdf.format(d);
if((d.after(startDate) && (d.before(endDate))) || (currDt.equals(sdf.format(startDate)) ||currDt.equals(sdf.format(endDate)))){
System.out.println("Date is between 1st april to 14th nov...");
}
else{
System.out.println("Date is not between 1st april to 14th nov...");
}
}
How to check if a String contains another String in a case insensitive manner in Java?
We can use stream with anyMatch and contains of Java 8
public class Test2 {
public static void main(String[] args) {
String a = "Gina Gini Protijayi Soudipta";
String b = "Gini";
System.out.println(WordPresentOrNot(a, b));
}// main
private static boolean WordPresentOrNot(String a, String b) {
//contains is case sensitive. That's why change it to upper or lower case. Then check
// Here we are using stream with anyMatch
boolean match = Arrays.stream(a.toLowerCase().split(" ")).anyMatch(b.toLowerCase()::contains);
return match;
}
}
The performance impact of using instanceof in Java
'instanceof' is actually an operator, like + or -, and I believe that it has its own JVM bytecode instruction. It should be plenty fast.
I should not that if you have a switch where you are testing if an object is an instance of some subsclass, then your design might need to be reworked. Consider pushing the subclass-specific behavior down into the subclasses themselves.
Adding a column to an existing table in a Rails migration
To add a column I just had to follow these steps :
rails generate migration add_fieldname_to_tablename fieldname:string
Alternative
rails generate migration addFieldnameToTablename
Once the migration is generated, then edit the migration and define all the attributes you want that column added to have.
Note: Table names in Rails are always plural (to match DB conventions). Example using one of the steps mentioned previously-
rails generate migration addEmailToUsers
rake db:migrate
Or
- You can change the schema in from
db/schema.rb
, Add the columns you want in the SQL query.
Run this command: rake db:schema:load
Warning/Note
Bear in mind that, running rake db:schema:load
automatically wipes all data in your tables.
Python 3: ImportError "No Module named Setuptools"
EDIT: Official setuptools dox page:
If you have Python 2 >=2.7.9 or Python 3 >=3.4 installed from
python.org, you will already have pip and setuptools, but will need to
upgrade to the latest version:
On Linux or OS X:
pip install -U pip setuptools
On Windows:
python -m pip install -U pip setuptools
Therefore the rest of this post is probably obsolete (e.g. some links don't work).
Distribute - is a setuptools fork which "offers Python 3 support". Installation instructions for distribute(setuptools) + pip:
curl -O http://python-distribute.org/distribute_setup.py
python distribute_setup.py
easy_install pip
Similar issue here.
UPDATE: Distribute seems to be obsolete, i.e. merged into Setuptools: Distribute is a deprecated fork of the Setuptools project. Since the Setuptools 0.7 release, Setuptools and Distribute have merged and Distribute is no longer being maintained. All ongoing effort should reference the Setuptools project and the Setuptools documentation.
You may try with instructions found on setuptools pypi page (I haven't tested this, sorry :( ):
wget https://bitbucket.org/pypa/setuptools/raw/bootstrap/ez_setup.py -O - | python
easy_install pip
Check if multiple strings exist in another string
A compact way to find multiple strings in another list of strings is to use set.intersection. This executes much faster than list comprehension in large sets or lists.
>>> astring = ['abc','def','ghi','jkl','mno']
>>> bstring = ['def', 'jkl']
>>> a_set = set(astring) # convert list to set
>>> b_set = set(bstring)
>>> matches = a_set.intersection(b_set)
>>> matches
{'def', 'jkl'}
>>> list(matches) # if you want a list instead of a set
['def', 'jkl']
>>>
Java finished with non-zero exit value 2 - Android Gradle
For me the problem was, i had put a unnecessary complie library code in build.gradle
dependencies {
compile 'com.google.android.gms:play-services:7.5.0'
}
which was causing over 65k methods, so removed it,gradle sync, cleaned project, and then ran again and then this error stopped.
I needed just maps and gcm so i put these lines and synced project
compile 'com.google.android.gms:play-services-gcm:7.5.0'
compile 'com.google.android.gms:play-services-location:7.5.0'
Hi people i again encountered this problem and this time it was because of changing build tools version and it really required me to enable multidex..so i added these my app's build.gradle file..
defaultConfig {
applicationId "com.am.android"
minSdkVersion 13
targetSdkVersion 23
// Enabling multidex support.
multiDexEnabled true
}
dexOptions {
incremental true
javaMaxHeapSize "2048M"
jumboMode = true
}
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
compile 'com.android.support:multidex:1.0.1'
}
And create a class that extends Application class and include this method inside the class..
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
MultiDex.install(this);
}
also include in OnCreate method too
@Override
public void onCreate() {
MultiDex.install(this);
super.onCreate();
}
Creating columns in listView and add items
listView1.View = View.Details;
listView1.Columns.Add("Target No.", 83, HorizontalAlignment.Center);
listView1.Columns.Add(" Range ", 100, HorizontalAlignment.Center);
listView1.Columns.Add(" Azimuth ", 100, HorizontalAlignment.Center);
i also had same problem .. i drag column to left .. but now ok .. so let's say i have 283*196 size of listview ..... We declared in the column width -2 for auto width .. For fitting in the listview ,we can divide listview width into 3 parts (83,100,100) ...
Multiple connections to a server or shared resource by the same user, using more than one user name, are not allowed
Follow these steps:
- Select the
Start
button, then type cmd
.
- Right-click the
Command Prompt
option, then choose Run as administrator
.
- Type
net use
, then press Enter
.
- Look for any drives listed that may be questionable. In many cases where this problem occurs, the drive may not be assigned a letter. You’ll want to remove that drive.
- From the Command Prompt, type
net use /delete \\servername\foldername
where the servername\foldername is the drive that you wish to delete.
How do I put two increment statements in a C++ 'for' loop?
Use Maths. If the two operations mathematically depend on the loop iteration, why not do the math?
int i, j;//That have some meaningful values in them?
for( int counter = 0; counter < count_max; ++counter )
do_something (counter+i, counter+j);
Or, more specifically referring to the OP's example:
for(int i = 0; i != 5; ++i)
do_something(i, j+i);
Especially if you're passing into a function by value, then you should get something that does exactly what you want.
JDBC ODBC Driver Connection
Didn't work with ODBC-Bridge for me too.
I got the way around to initialize ODBC connection using ODBC driver.
import java.sql.*;
public class UserLogin
{
public static void main(String[] args)
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
// C:\\databaseFileName.accdb" - location of your database
String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=" + "C:\\emp.accdb";
// specify url, username, pasword - make sure these are valid
Connection conn = DriverManager.getConnection(url, "username", "password");
System.out.println("Connection Succesfull");
}
catch (Exception e)
{
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
}
}
Column order manipulation using col-lg-push and col-lg-pull in Twitter Bootstrap 3
I just felt like I'll add my $0.2 to those 2 good answers. I had a case when I had to move the last column all the way to the top in a 3-column situation.
[A][B][C]
to
[C]
[A]
[B]
Boostrap's class .col-xx-push-X
does nothing else but pushes a column to the right with left: XX%;
so all you have to do to push a column right is to add the number of pseudo columns going left.
In this case:
two columns (col-md-5
and col-md-3
) are going left, each with the value of the one that is going right;
one(col-md-4
) is going right by the sum of the first two going left (5+3=8);
<div class="row">
<div class="col-md-4 col-md-push-8 ">
C
</div>
<div class="col-md-5 col-md-pull-4">
A
</div>
<div class="col-md-3 col-md-pull-4">
B
</div>
</div>
Xcode 4 - build output directory
Another thing to check before you start playing with Xcode preferences is:
Select your target and go to Build Settings > Packaging > Wrapper Extension
The value there should be: app
If not double click it and type "app" without the qoutes.
Home does not contain an export named Home
You can use two ways to resolve this problem, first way that i think it as best way is replace importing segment of your code with bellow one:
import Home from './layouts/Home'
or export your component without default which is called named export like this
import React, { Component } from 'react';
class Home extends Component{
render(){
return(
<p className="App-intro">
Hello Man
</p>
)
}
}
export {Home};
Python: convert string from UTF-8 to Latin-1
If the previous answers do not solve your problem, check the source of the data that won't print/convert properly.
In my case, I was using json.load
on data incorrectly read from file by not using the encoding="utf-8"
. Trying to de-/encode the resulting string to latin-1
just does not help...
Ways to insert javascript into URL?
old question that I stumbled into that I believe deserves an update... You can infact execute javascript from the URL, and you can get creative about it too. I recently made a members only area that I wanted to remind someone what their password was, so I was looking for a non-local alert...of course you can embed an alert into the page itself, but then its public. the difference here is I can create a link and slip some JS into the href so clicking on the link will generate the alert.
here is what I mean >>
<a href="javascript:alert('the secret is to ask.');window.location.replace('http://google.com');">You can have anything</a>
and so upon clicking the link, the user is given an alert with the info, then they are taken to the new page.
obviously you could also write an onClick, but the href works just fine when you slip it through the URL, just remember to prepend it with "javascript:"
*works in chrome, didnt check anything else.
Converting a generic list to a CSV string
For whatever reason, @AliUmair reverted the edit to his answer that fixes his code that doesn't run as is, so here is the working version that doesn't have the file access error and properly handles null object property values:
/// <summary>
/// Creates the CSV from a generic list.
/// </summary>;
/// <typeparam name="T"></typeparam>;
/// <param name="list">The list.</param>;
/// <param name="csvNameWithExt">Name of CSV (w/ path) w/ file ext.</param>;
public static void CreateCSVFromGenericList<T>(List<T> list, string csvCompletePath)
{
if (list == null || list.Count == 0) return;
//get type from 0th member
Type t = list[0].GetType();
string newLine = Environment.NewLine;
if (!Directory.Exists(Path.GetDirectoryName(csvCompletePath))) Directory.CreateDirectory(Path.GetDirectoryName(csvCompletePath));
using (var sw = new StreamWriter(csvCompletePath))
{
//make a new instance of the class name we figured out to get its props
object o = Activator.CreateInstance(t);
//gets all properties
PropertyInfo[] props = o.GetType().GetProperties();
//foreach of the properties in class above, write out properties
//this is the header row
sw.Write(string.Join(",", props.Select(d => d.Name).ToArray()) + newLine);
//this acts as datarow
foreach (T item in list)
{
//this acts as datacolumn
var row = string.Join(",", props.Select(d => $"\"{item.GetType().GetProperty(d.Name).GetValue(item, null)?.ToString()}\"")
.ToArray());
sw.Write(row + newLine);
}
}
}
Pretty printing JSON from Jackson 2.2's ObjectMapper
According to mkyong, the magic incantation is defaultPrintingWriter
to pretty print JSON:
Newer versions:
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonInstance));
Older versions:
System.out.println(mapper.defaultPrettyPrintingWriter().writeValueAsString(jsonInstance));
Seems I jumped the gun a tad quickly. You could try gson, whose constructor supports pretty-printing:
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String jsonOutput = gson.toJson(someObject);
Hope this helps...
What is the correct syntax for 'else if'?
In python "else if" is spelled "elif".
Also, you need a colon after the elif
and the else
.
Simple answer to a simple question. I had the same problem, when I first started (in the last couple of weeks).
So your code should read:
def function(a):
if a == '1':
print('1a')
elif a == '2':
print('2a')
else:
print('3a')
function(input('input:'))
Get last 3 characters of string
The easiest way would be using Substring
string str = "AM0122200204";
string substr = str.Substring(str.Length - 3);
Using the overload with one int
as I put would get the substring
of a string
, starting from the index int
. In your case being str.Length - 3
, since you want to get the last three chars.
SQL Server Configuration Manager not found
For SQL Server 2017 it is : C:\Windows\SysWOW64\SQLServerManager14.msc
For SQL Server 2016 it is : C:\Windows\SysWOW64\SQLServerManager13.msc
For SQL Server 2016 it is :C:\Windows\SysWOW64\SQLServerManager12.msc
and to add it back to the start menu, copy it from the original location provided above and paste it to
C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Microsoft SQL Server 2017\Configuration Tools\
This would put back the configuration manager under start menu.
Source: How to open sql server configuration manager in windows 10?
Best way to pretty print a hash
require 'pp'
pp my_hash
Use pp
if you need a built-in solution and just want reasonable line breaks.
Use awesome_print if you can install a gem. (Depending on your users, you may wish to use the index:false
option to turn off displaying array indices.)
How do I run a simple bit of code in a new thread?
There are many ways of running separate threads in .Net, each has different behaviors. Do you need to continue running the thread after the GUI quits? Do you need to pass information between the thread and GUI? Does the thread need to update the GUI? Should the thread do one task then quit, or should it continue running? The answers to these questions will tell you which method to use.
There is a good async method article at the Code Project web site that describes the various methods and provides sample code.
Note this article was written before the async/await pattern and Task Parallel Library were introduced into .NET.
How to send POST request?
If you need your script to be portable and you would rather not have any 3rd party dependencies, this is how you send POST request purely in Python 3.
from urllib.parse import urlencode
from urllib.request import Request, urlopen
url = 'https://httpbin.org/post' # Set destination URL here
post_fields = {'foo': 'bar'} # Set POST fields here
request = Request(url, urlencode(post_fields).encode())
json = urlopen(request).read().decode()
print(json)
Sample output:
{
"args": {},
"data": "",
"files": {},
"form": {
"foo": "bar"
},
"headers": {
"Accept-Encoding": "identity",
"Content-Length": "7",
"Content-Type": "application/x-www-form-urlencoded",
"Host": "httpbin.org",
"User-Agent": "Python-urllib/3.3"
},
"json": null,
"origin": "127.0.0.1",
"url": "https://httpbin.org/post"
}
Validate Dynamically Added Input fields
In regards to @RitchieD response, here is a jQuery plugin version to make things easier if you are using jQuery.
(function ($) {
$.fn.initValidation = function () {
$(this).removeData("validator");
$(this).removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse(this);
return this;
};
}(jQuery));
This can be used like this:
$("#SomeForm").initValidation();
MySql : Grant read only options?
A step by step guide I found here.
To create a read-only database user account for MySQL
At a UNIX prompt, run the MySQL command-line program, and log in as an administrator by typing the following command:
mysql -u root -p
Type the password for the root account.
At the mysql prompt, do one of the following steps:
To give the user access to the database from any host, type the following command:
grant select on database_name.* to 'read-only_user_name'@'%' identified by 'password';
If the collector will be installed on the same host as the database, type the following command:
grant select on database_name.* to 'read-only_user_name' identified by 'password';
This command gives the user read-only access to the database from the local host only.
If you know the host name or IP address of the host that the collector is will be installed on, type the following command:
grant select on database_name.* to 'read-only_user_name'@'host_name or IP_address' identified by 'password';
The host name must be resolvable by DNS or by the local hosts file.
At the mysql prompt, type the following command:
flush privileges;
Type quit
.
The following is a list of example commands and confirmation messages:
mysql> grant select on dbname.* to 'readonlyuser'@'%' identified
by 'pogo$23';
Query OK, 0 rows affected (0.11 sec)
mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)
mysql> quit
Java AES and using my own Key
byte[] seed = (SALT2 + username + password).getBytes();
SecureRandom random = new SecureRandom(seed);
KeyGenerator generator;
generator = KeyGenerator.getInstance("AES");
generator.init(random);
generator.init(256);
Key keyObj = generator.generateKey();
Bash: Strip trailing linebreak from output
If you want to print output of anything in Bash without end of line, you echo it with the -n
switch.
If you have it in a variable already, then echo it with the trailing newline cropped:
$ testvar=$(wc -l < log.txt)
$ echo -n $testvar
Or you can do it in one line, instead:
$ echo -n $(wc -l < log.txt)
SQLAlchemy IN clause
How about
session.query(MyUserClass).filter(MyUserClass.id.in_((123,456))).all()
edit: Without the ORM, it would be
session.execute(
select(
[MyUserTable.c.id, MyUserTable.c.name],
MyUserTable.c.id.in_((123, 456))
)
).fetchall()
select()
takes two parameters, the first one is a list of fields to retrieve, the second one is the where
condition. You can access all fields on a table object via the c
(or columns
) property.
Resize image in the wiki of GitHub using Markdown
This addresses the different question, how to get images in gist (as opposed to github) markdown in the first place ?
In December 2015, it seems that only links to files on
github.com
or
cloud.githubusercontent.com
or the like work.
Steps that worked for me in a gist:
- Make a gist, say
Mygist.md
(and optionally more files)
- Go to the "Write Comment" box at the end
- Click "Attach files ... by selecting them"; select your local image file
- GitHub echos a long long string where it put the image, e.g.
![khan-lasso-squared](https://cloud.githubusercontent.com/assets/1280390/12011119/596fdca4-acc2-11e5-84d0-4878164e04bb.png)
- Cut-paste that by hand into your
Mygist.md
.
But: GitHub people may change this behavior tomorrow, without documenting it.
How do I abort the execution of a Python script?
You could put the body of your script into a function and then you could return from that function.
def main():
done = True
if done:
return
# quit/stop/exit
else:
# do other stuff
if __name__ == "__main__":
#Run as main program
main()
SELECT INTO using Oracle
If NEW_TABLE already exists then ...
insert into new_table
select * from old_table
/
If you want to create NEW_TABLE based on the records in OLD_TABLE ...
create table new_table as
select * from old_table
/
If the purpose is to create a new but empty table then use a WHERE clause with a condition which can never be true:
create table new_table as
select * from old_table
where 1 = 2
/
Remember that CREATE TABLE ... AS SELECT creates only a table with the same projection as the source table. The new table does not have any constraints, triggers or indexes which the original table might have. Those still have to be added manually (if they are required).
Using ffmpeg to encode a high quality video
A couple of things:
You need to set the video bitrate. I have never used minrate and maxrate so I don't know how exactly they work, but by setting the bitrate using the -b
switch, I am able to get high quality video. You need to come up with a bitrate that offers a good tradeoff between compression and video quality. You may have to experiment with this because it all depends on the frame size, frame rate and the amount of motion in the content of your video. Keep in mind that DVD tends to be around 4-5 Mbit/s on average for 720x480, so I usually start from there and decide whether I need more or less and then just experiment. For example, you could add -b 5000k
to the command line to get more or less DVD video bitrate.
You need to specify a video codec. If you don't, ffmpeg will default to MPEG-1 which is quite old and does not provide near the amount of compression as MPEG-4 or H.264. If your ffmpeg version is built with libx264 support, you can specify -vcodec libx264
as part of the command line. Otherwise -vcodec mpeg4
will also do a better job than MPEG-1, but not as well as x264.
There are a lot of other advanced options that will help you squeeze out the best quality at the lowest bitrates. Take a look here for some examples.
PHP with MySQL 8.0+ error: The server requested authentication method unknown to the client
i've try a lot of ways, but only this work for me
thanks for workaround
check your .env
MYSQL_VERSION=latest
then type this command
$ docker-compose exec mysql bash
$ mysql -u root -p
(login as root)
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'root';
ALTER USER 'root'@'%' IDENTIFIED WITH mysql_native_password BY 'root';
ALTER USER 'default'@'%' IDENTIFIED WITH mysql_native_password BY 'secret';
then go to phpmyadmin and login as :
- host -> mysql
- user -> root
- password -> root
hope it help
Altering a column: null to not null
I had the same problem, but the field used to default to null, and now I want to default it to 0. That required adding one more line after mdb's solution:
ALTER TABLE [Table] ADD CONSTRAINT [Constraint] DEFAULT 0 FOR [Column];
jQuery UI 1.10: dialog and zIndex option
There are multiple suggestions here, but as far as I can see the jQuery UI guys have broken the dialogue control at present.
I say this because I include a dialogue on my page, and its semi transparent and the modal blanking div is behind some other elements. That can't be right!
In the end based on some other posts I developed this global solution, as an extension to the dialogue widget. It works for me but I'm not sure what it would do if I opened a dialogue from within a dialogue.
Basically it looks for the zIndex of everything else on the page and moves the .ui-widget-overlay to be one higher, and the dialogue itself to be one higher than that.
$.widget("ui.dialog", $.ui.dialog,
{
open: function ()
{
var $dialog = $(this.element[0]);
var maxZ = 0;
$('*').each(function ()
{
var thisZ = $(this).css('zIndex');
thisZ = (thisZ === 'auto' ? (Number(maxZ) + 1) : thisZ);
if (thisZ > maxZ) maxZ = thisZ;
});
$(".ui-widget-overlay").css("zIndex", (maxZ + 1));
$dialog.parent().css("zIndex", (maxZ + 2));
return this._super();
}
});
Thanks to the following, as this is where I got the info from of how to do this:
https://stackoverflow.com/a/20942857
http://learn.jquery.com/jquery-ui/widget-factory/extending-widgets/
first-child and last-child with IE8
If your table is only 2 columns across, you can easily reach the second td
with the adjacent sibling selector, which IE8 does support along with :first-child
:
.editor td:first-child
{
width: 150px;
}
.editor td:first-child + td input,
.editor td:first-child + td textarea
{
width: 500px;
padding: 3px 5px 5px 5px;
border: 1px solid #CCC;
}
Otherwise, you'll have to use a JS selector library like jQuery, or manually add a class to the last td
, as suggested by James Allardice.
Oracle PL/SQL - How to create a simple array variable?
You could just declare a DBMS_SQL.VARCHAR2_TABLE to hold an in-memory variable length array indexed by a BINARY_INTEGER:
DECLARE
name_array dbms_sql.varchar2_table;
BEGIN
name_array(1) := 'Tim';
name_array(2) := 'Daisy';
name_array(3) := 'Mike';
name_array(4) := 'Marsha';
--
FOR i IN name_array.FIRST .. name_array.LAST
LOOP
-- Do something
END LOOP;
END;
You could use an associative array (used to be called PL/SQL tables) as they are an in-memory array.
DECLARE
TYPE employee_arraytype IS TABLE OF employee%ROWTYPE
INDEX BY PLS_INTEGER;
employee_array employee_arraytype;
BEGIN
SELECT *
BULK COLLECT INTO employee_array
FROM employee
WHERE department = 10;
--
FOR i IN employee_array.FIRST .. employee_array.LAST
LOOP
-- Do something
END LOOP;
END;
The associative array can hold any make up of record types.
Hope it helps,
Ollie.
pySerial write() won't take my string
It turns out that the string needed to be turned into a bytearray and to do this I editted the code to
ser.write("%01#RDD0010000107**\r".encode())
This solved the problem
Get the Id of current table row with Jquery
First, your jQuery will not work at all unless you enclose all your tr
s and td
s in a table:
<table>
<tr>...</tr>
...
</table>
Second, your code gets the id
of the first tr
of the page, since you select all the tr
s of the page and get the id
of the first one (.attr()
returns the attribute of the first element in the set of elements it is used on)
Your current code:
$('input[type=button]' ).click(function() {
bid = (this.id) ; // button ID
trid = $('tr').attr('id'); // ID of the the first TR on the page
// $('tr') selects all trs in the DOM
});
Instead of selecting all tr
s on the page with $('tr')
, you want to select the first ancestor of the clicked upon input
that is a tr
. Use .closest()
for this in the form $(this).closest('tr')
.
You can reference the clicked on element as this
, make a jQuery object out of it with the form $(this)
, so you have access to all the jQuery methods on it.
What your code should look like:
// On DOM ready...
$(function() {
$('input[type=button]' ).click(function() {
var bid, trid; // Declare variables. If you don't use var
// you will bind bid and trid
// to the window, since you make them global variables.
bid = (this.id) ; // button ID
trid = $(this).closest('tr').attr('id'); // table row ID
});
});
Simple dynamic breadcrumb
hey dominic your answer was nice but if your have a site like http://localhost/project/index.php the 'project' link gets repeated since it's part of $base and also appears in the $path array. So I tweaked and removed the first item in the $path array.
//Trying to remove the first item in the array path so it doesn't repeat
array_shift($path);
I dont know if that is the most elegant way, but it now works for me.
I add that code before this one on line 13 or something
// Find out the index for the last value in our path array
$last = end(array_keys($path));
The provided URI scheme 'https' is invalid; expected 'http'. Parameter name: via
Ran into the same issue, this is how my solution turned out at the end:
<basicHttpsBinding>
<binding name="VerificationServicesPasswordBinding">
<security mode="Transport">
</security>
</binding>
<binding name="VerificationServicesPasswordBinding1" />
</basicHttpsBinding>
I basically replaced every occurrence of Http with Https. You can try adding both of them if you prefer.
Error:java: javacTask: source release 8 requires target release 1.8
With Intellij, using Maven, you must check that Intellij has auto-imported your project.
You can check by clicking on the Maven tab on the right of your Editor.
If your Project is not here, then add the pom.xml
file by clicking on +
.
Obviously, the project must also have the relevant <build/>
:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
How to convert String into Hashmap in java
You can do it in single line, for any object type not just Map.
(Since I use Gson quite liberally, I am sharing a Gson based approach)
Gson gson = new Gson();
Map<Object,Object> attributes = gson.fromJson(gson.toJson(value),Map.class);
What it does is:
gson.toJson(value)
will serialize your object into its equivalent Json representation.
gson.fromJson
will convert the Json string to specified object. (in this example - Map
)
There are 2 advantages with this approach:
- The flexibility to pass an Object instead of String to
toJson
method.
- You can use this single line to convert to any object even your own declared objects.
How do I redirect to the previous action in ASP.NET MVC?
Pass a returnUrl parameter (url encoded) to the change and login actions and inside redirect to this given returnUrl. Your login action might look something like this:
public ActionResult Login(string returnUrl)
{
// Do something...
return Redirect(returnUrl);
}
Locating child nodes of WebElements in selenium
According to JavaDocs, you can do this:
WebElement input = divA.findElement(By.xpath(".//input"));
How can I ask in xpath for "the div-tag that contains a span with the
text 'hello world'"?
WebElement elem = driver.findElement(By.xpath("//div[span[text()='hello world']]"));
The XPath spec is a suprisingly good read on this.
How do you extract IP addresses from files using a regex in a linux shell?
I have tried all answers but all of them had one or many problems that I list a few of them.
- Some detected
123.456.789.111
as valid IP
- Some don't detect
127.0.00.1
as valid IP
- Some don't detect IP that start with zero like
08.8.8.8
So here I post a regex that works on all above conditions.
Note : I have extracted more than 2 millions IP without any problem with following regex.
(?:(?:1\d\d|2[0-5][0-5]|2[0-4]\d|0?[1-9]\d|0?0?\d)\.){3}(?:1\d\d|2[0-5][0-5]|2[0-4]\d|0?[1-9]\d|0?0?\d)
How do I download the Android SDK without downloading Android Studio?
What worked for me on Windows:
- Downloaded command line tools from https://developer.android.com/studio/index.html
- Put the whole
tools
folder from the ZIP archive to C:\Program Files (x86)\Android SDK\
- Launched
tools\android.bat
as administrator, which opened the usual SDK Manager window
- Installed required components. The files were downloaded to
...\Android SDK\
directory (that is build-tools
, platforms
, platform-tools
, etc. directories appeared alongside tools
inside ...\Android SDK\
)
- Opened the Android project in Intellij IDEA, navigated to File->Project Structure->SDKs, and added Android SDK by directing to
...\Android SDK\
directory
Git: How to return from 'detached HEAD' state
Use git reflog
to find the hashes of previously checked out commits.
A shortcut command to get to your last checked out branch (not sure if this work correctly with detached HEAD and intermediate commits though) is git checkout -
Open page in new window without popup blocking
PS> I posted this answer on a related question. Here's how I got round the issue of my async ajax request losing the trusted context:
I opened the popup directly on the users click, directed the url to about:blank
and got a handle on that window. You could probably direct the popup to a 'loading' url while your ajax request is made
var myWindow = window.open("about:blank",'name','height=500,width=550');
Then, when my request is successful, I open my callback url in the window
function showWindow(win, url) {
win.open(url,'name','height=500,width=550');
}
Standardize data columns in R
Again, even though this is an old question, it is very relevant! And I have found a simple way to normalise certain columns without the need of any packages:
normFunc <- function(x){(x-mean(x, na.rm = T))/sd(x, na.rm = T)}
For example
x<-rnorm(10,14,2)
y<-rnorm(10,7,3)
z<-rnorm(10,18,5)
df<-data.frame(x,y,z)
df[2:3] <- apply(df[2:3], 2, normFunc)
You will see that the y and z columns have been normalised. No packages needed :-)
Allowed characters in filename
To be more precise about Mac OS X (now called MacOS) /
in the Finder is interpreted to :
in the Unix file system.
This was done for backward compatibility when Apple moved from Classic Mac OS.
It is legitimate to use a /
in a file name in the Finder, looking at the same file in the terminal it will show up with a :
.
And it works the other way around too: you can't use a /
in a file name with the terminal, but a :
is OK and will show up as a /
in the Finder.
Some applications may be more restrictive and prohibit both characters to avoid confusion or because they kept logic from previous Classic Mac OS or for name compatibility between platforms.
How to increase the Java stack size?
I assume you calculated the "depth of 1024" by the recurring lines in the stack trace?
Obviously, the stack trace array length in Throwable seems to be limited to 1024.
Try the following program:
public class Test {
public static void main(String[] args) {
try {
System.out.println(fact(1 << 15));
}
catch (StackOverflowError e) {
System.err.println("true recursion level was " + level);
System.err.println("reported recursion level was " +
e.getStackTrace().length);
}
}
private static int level = 0;
public static long fact(int n) {
level++;
return n < 2 ? n : n * fact(n - 1);
}
}
Execute JavaScript using Selenium WebDriver in C#
How about a slightly simplified version of @Morten Christiansen's nice extension method idea:
public static object Execute(this IWebDriver driver, string script)
{
return ((IJavaScriptExecutor)driver).ExecuteScript(script);
}
// usage
var title = (string)driver.Execute("return document.title");
or maybe the generic version:
public static T Execute<T>(this IWebDriver driver, string script)
{
return (T)((IJavaScriptExecutor)driver).ExecuteScript(script);
}
// usage
var title = driver.Execute<string>("return document.title");
Simple If/Else Razor Syntax
A little bit off topic maybe, but for modern browsers (IE9 and newer) you can use the css odd/even selectors to achieve want you want.
tr:nth-child(even) { /* your alt-row stuff */}
tr:nth-child(odd) { /* the other rows */ }
or
tr { /* all table rows */ }
tr:nth-child(even) { /* your alt-row stuff */}
Global variables in c#.net
I second jdk's answer: any public static member of any class of your application can be considered as a "global variable".
However, do note that this is an ASP.NET application, and as such, it's a multi-threaded context for your global variables. Therefore, you should use some locking mechanism when you update and/or read the data to/from these variables. Otherwise, you might get your data in a corrupted state.
Select a Dictionary<T1, T2> with LINQ
A more explicit option is to project collection to an IEnumerable of KeyValuePair
and then convert it to a Dictionary.
Dictionary<int, string> dictionary = objects
.Select(x=> new KeyValuePair<int, string>(x.Id, x.Name))
.ToDictionary(x=>x.Key, x=>x.Value);
xsd:boolean element type accept "true" but not "True". How can I make it accept it?
If you're on Linux, or have cygwin available on Windows, you can run the input XML through a simple sed script that will replace <Active>True</Active>
with <Active>true</Active>
, like so:
cat <your XML file> | sed 'sX<Active>True</Active>X<Active>true</Active>X' | xmllint --schema -
If you're not, you can still use a non-validating xslt pocessor (xalan, saxon etc.) to run a simple xslt transformation on the input, and only then pipe it to xmllint.
What the xsl should contain something like below, for the example you listed above (the xslt processor should be 2.0 capable):
<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="/">
<xsl:for-each select="XML">
<xsl:for-each select="Active">
<xsl:value-of select=" replace(current(), 'True','true')"/>
</xsl:for-each>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
Storing query results into a variable and modifying it inside a Stored Procedure
Try this example
CREATE PROCEDURE MyProc
BEGIN
--Stored Procedure variables
Declare @maxOr int;
Declare @maxCa int;
--Getting query result in the variable (first variant of syntax)
SET @maxOr = (SELECT MAX(orId) FROM [order]);
--Another variant of seting variable from query
SELECT @maxCa=MAX(caId) FROM [cart];
--Updating record through the variable
INSERT INTO [order_cart] (orId,caId)
VALUES(@maxOr, @maxCa);
--return values to the program as dataset
SELECT
@maxOr AS maxOr,
@maxCa AS maxCa
-- return one int value as "return value"
RETURN @maxOr
END
GO
SQL-command to call the stored procedure
EXEC MyProc
T-SQL CASE Clause: How to specify WHEN NULL
You can use IsNull function
select
isnull(rtrim(ltrim([FirstName]))+' ','') +
isnull(rtrim(ltrim([SecondName]))+' ','') +
isnull(rtrim(ltrim([Surname]))+' ','') +
isnull(rtrim(ltrim([SecondSurname])),'')
from TableDat
if one column is null you would get an empty char
Compatible with Microsoft SQL Server 2008+
Hibernate Criteria Restrictions AND / OR combination
For the new Criteria since version Hibernate 5.2:
CriteriaBuilder criteriaBuilder = getSession().getCriteriaBuilder();
CriteriaQuery<SomeClass> criteriaQuery = criteriaBuilder.createQuery(SomeClass.class);
Root<SomeClass> root = criteriaQuery.from(SomeClass.class);
Path<Object> expressionA = root.get("A");
Path<Object> expressionB = root.get("B");
Predicate predicateAEqualX = criteriaBuilder.equal(expressionA, "X");
Predicate predicateBInXY = expressionB.in("X",Y);
Predicate predicateLeft = criteriaBuilder.and(predicateAEqualX, predicateBInXY);
Predicate predicateAEqualY = criteriaBuilder.equal(expressionA, Y);
Predicate predicateBEqualZ = criteriaBuilder.equal(expressionB, "Z");
Predicate predicateRight = criteriaBuilder.and(predicateAEqualY, predicateBEqualZ);
Predicate predicateResult = criteriaBuilder.or(predicateLeft, predicateRight);
criteriaQuery
.select(root)
.where(predicateResult);
List<SomeClass> list = getSession()
.createQuery(criteriaQuery)
.getResultList();
How to unzip a file in Powershell?
Hey Its working for me..
$shell = New-Object -ComObject shell.application
$zip = $shell.NameSpace("put ur zip file path here")
foreach ($item in $zip.items()) {
$shell.Namespace("destination where files need to unzip").CopyHere($item)
}
A Java collection of value pairs? (tuples?)
You could write a generic Pair<A, B> class and use this in an array or list. Yes, you have to write a class, but you can reuse the same class for all types, so you only have to do it once.
nodejs npm global config missing on windows
It looks like the files npm
uses to edit its config files are not created on a clean install, as npm
has a default option for each one. This is why you can still get options with npm config get <option>
: having those files only overrides the defaults, it doesn't create the options from scratch.
I had never touched my npm config
stuff before today, even though I had had it for months now. None of the files were there yet, such as ~/.npmrc
(on a Windows 8.1 machine with Git Bash
), yet I could run npm config get <something>
and, if it was a correct npm
option, it returned a value. When I ran npm config set <option> <value>
, the file ~/.npmrc
seemed to be created automatically, with the option & its value as the only non-commented-out line.
As for deleting options, it looks like this just sets the value back to the default value, or does nothing if that option was never set or was unset & never reset. Additionally, if that option is the only explicitly set option, it looks like ~/.npmrc
is deleted, too, and recreated if you set
anything else later.
In your case (assuming it is still the same over a year later), it looks like you never set the proxy
option in npm
. Therefore, as npm
's config
help page says, it is set to whatever your http_proxy
(case-insensitive) environment variable is. This means there is nothing to delete
, unless you want to "delete" your HTTP proxy, although you could set
the option or environment variable to something else and hope neither breaks your set-up somehow.
System.IO.IOException: file used by another process
After coming across this error and not finding anything on the web that set me right, I thought I'd add another reason for getting this Exception - namely that the source and destination paths in the File Copy command are the same. It took me a while to figure it out, but it may help to add code somewhere to throw an exception if source and destination paths are pointing to the same file.
Good luck!
.war vs .ear file
A WAR (Web Archive) is a module that gets loaded into a Web container of a Java Application Server. A Java Application Server has two containers (runtime environments) - one is a Web container and the other is a EJB container.
The Web container hosts Web applications based on JSP or the Servlets API - designed specifically for web request handling - so more of a request/response style of distributed computing. A Web container requires the Web module to be packaged as a WAR file - that is a special JAR file with a web.xml
file in the WEB-INF
folder.
An EJB container hosts Enterprise java beans based on the EJB API designed to provide extended business functionality such as declarative transactions, declarative method level security and multiprotocol support - so more of an RPC style of distributed computing. EJB containers require EJB modules to be packaged as JAR files - these have an ejb-jar.xml
file in the META-INF
folder.
Enterprise applications may consist of one or more modules that can either be Web modules (packaged as a WAR file), EJB modules (packaged as a JAR file), or both of them. Enterprise applications are packaged as EAR files - these are special JAR files containing an application.xml
file in the META-INF
folder.
Basically, EAR files are a superset containing WAR files and JAR files. Java Application Servers allow deployment of standalone web modules in a WAR file, though internally, they create EAR files as a wrapper around WAR files. Standalone web containers such as Tomcat and Jetty do not support EAR files - these are not full-fledged Application servers. Web applications in these containers are to be deployed as WAR files only.
In application servers, EAR files contain configurations such as application security role mapping, EJB reference mapping and context root URL mapping of web modules.
Apart from Web modules and EJB modules, EAR files can also contain connector modules packaged as RAR files and Client modules packaged as JAR files.
A cron job for rails: best practices?
I'm using the rake approach (as supported by heroku)
With a file called lib/tasks/cron.rake ..
task :cron => :environment do
puts "Pulling new requests..."
EdiListener.process_new_messages
puts "done."
end
To execute from the command line, this is just "rake cron". This command can then be put on the operating system cron/task scheduler as desired.
Update this is quite an old question and answer! Some new info:
- the heroku cron service I referenced has since been replaced by Heroku Scheduler
- for frequent tasks (esp. where you want to avoid the Rails environment startup cost) my preferred approach is to use system cron to call a script that will either (a) poke a secure/private webhook API to invoke the required task in the background or (b) directly enqueue a task on your queuing system of choice
Check if a number is odd or even in python
Use the modulo operator:
if wordLength % 2 == 0:
print "wordLength is even"
else:
print "wordLength is odd"
For your problem, the simplest is to check if the word is equal to its reversed brother. You can do that with word[::-1]
, which create the list from word
by taking every character from the end to the start:
def is_palindrome(word):
return word == word[::-1]
PHP Echo text Color
If it echoing out to a browser, you should use CSS. This would require also having the comment wrapped in an HTML tag. Something like:
echo '<p style="color: red; text-align: center">
Request has been sent. Please wait for my reply!
</p>';
Extract regression coefficient values
Just pass your regression model into the following function:
plot_coeffs <- function(mlr_model) {
coeffs <- coefficients(mlr_model)
mp <- barplot(coeffs, col="#3F97D0", xaxt='n', main="Regression Coefficients")
lablist <- names(coeffs)
text(mp, par("usr")[3], labels = lablist, srt = 45, adj = c(1.1,1.1), xpd = TRUE, cex=0.6)
}
Use as follows:
model <- lm(Petal.Width ~ ., data = iris)
plot_coeffs(model)
How to change text color of simple list item
If you are creating a class that extends an Adapter, you can use parent variable to obtain the context.
public class MyAdapter extends ArrayAdapter<String> {
private Context context;
@Override
public View getView(int position, View convertView, ViewGroup parent) {
context = parent.getContext();
context.getResources().getColor(R.color.red);
return convertView;
}
}
You can do the same with RecyclerView.Adapter, but instead of getview() you will use onCreateViewHolder().
How to get list of dates between two dates in mysql select query
Try:
select * from
(select adddate('1970-01-01',t4.i*10000 + t3.i*1000 + t2.i*100 + t1.i*10 + t0.i) selected_date from
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t0,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t1,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t2,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t3,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t4) v
where selected_date between '2012-02-10' and '2012-02-15'
-for date ranges up to nearly 300 years in the future.
[Corrected following a suggested edit by UrvishAtSynapse.]
Randomize a List<T>
Shuffle any (I)List
with an extension method based on the Fisher-Yates shuffle:
private static Random rng = new Random();
public static void Shuffle<T>(this IList<T> list)
{
int n = list.Count;
while (n > 1) {
n--;
int k = rng.Next(n + 1);
T value = list[k];
list[k] = list[n];
list[n] = value;
}
}
Usage:
List<Product> products = GetProducts();
products.Shuffle();
The code above uses the much criticised System.Random method to select swap candidates. It's fast but not as random as it should be. If you need a better quality of randomness in your shuffles use the random number generator in System.Security.Cryptography like so:
using System.Security.Cryptography;
...
public static void Shuffle<T>(this IList<T> list)
{
RNGCryptoServiceProvider provider = new RNGCryptoServiceProvider();
int n = list.Count;
while (n > 1)
{
byte[] box = new byte[1];
do provider.GetBytes(box);
while (!(box[0] < n * (Byte.MaxValue / n)));
int k = (box[0] % n);
n--;
T value = list[k];
list[k] = list[n];
list[n] = value;
}
}
A simple comparison is available at this blog (WayBack Machine).
Edit: Since writing this answer a couple years back, many people have commented or written to me, to point out the big silly flaw in my comparison. They are of course right. There's nothing wrong with System.Random if it's used in the way it was intended. In my first example above, I instantiate the rng variable inside of the Shuffle method, which is asking for trouble if the method is going to be called repeatedly. Below is a fixed, full example based on a really useful comment received today from @weston here on SO.
Program.cs:
using System;
using System.Collections.Generic;
using System.Threading;
namespace SimpleLottery
{
class Program
{
private static void Main(string[] args)
{
var numbers = new List<int>(Enumerable.Range(1, 75));
numbers.Shuffle();
Console.WriteLine("The winning numbers are: {0}", string.Join(", ", numbers.GetRange(0, 5)));
}
}
public static class ThreadSafeRandom
{
[ThreadStatic] private static Random Local;
public static Random ThisThreadsRandom
{
get { return Local ?? (Local = new Random(unchecked(Environment.TickCount * 31 + Thread.CurrentThread.ManagedThreadId))); }
}
}
static class MyExtensions
{
public static void Shuffle<T>(this IList<T> list)
{
int n = list.Count;
while (n > 1)
{
n--;
int k = ThreadSafeRandom.ThisThreadsRandom.Next(n + 1);
T value = list[k];
list[k] = list[n];
list[n] = value;
}
}
}
}
How can I SELECT rows with MAX(Column value), DISTINCT by another column in SQL?
You are so close! All you need to do is select BOTH the home and its max date time, then join back to the topten
table on BOTH fields:
SELECT tt.*
FROM topten tt
INNER JOIN
(SELECT home, MAX(datetime) AS MaxDateTime
FROM topten
GROUP BY home) groupedtt
ON tt.home = groupedtt.home
AND tt.datetime = groupedtt.MaxDateTime
R : how to simply repeat a command?
You could use replicate
or sapply
:
R> colMeans(replicate(10000, sample(100, size=815, replace=TRUE, prob=NULL))) R> sapply(seq_len(10000), function(...) mean(sample(100, size=815, replace=TRUE, prob=NULL)))
replicate
is a wrapper for the common use of sapply
for repeated evaluation of an expression (which will usually involve random number generation).
What is %timeit in python?
Line magics are prefixed with the % character and work much like OS command-line calls: they get as an argument the rest of the line, where arguments are passed without parentheses or quotes. Cell magics are prefixed with a double %%, and they are functions that get as an argument not only the rest of the line, but also the lines below it in a separate argument.
Is it a good practice to use try-except-else in Python?
Whenever you see this:
try:
y = 1 / x
except ZeroDivisionError:
pass
else:
return y
Or even this:
try:
return 1 / x
except ZeroDivisionError:
return None
Consider this instead:
import contextlib
with contextlib.suppress(ZeroDivisionError):
return 1 / x
SQL query to get most recent row for each instance of a given key
Both of the above answers assume that you only have one row for each user and time_stamp. Depending on the application and the granularity of your time_stamp this may not be a valid assumption. If you need to deal with ties of time_stamp for a given user, you'd need to extend one of the answers given above.
To write this in one query would require another nested sub-query - things will start getting more messy and performance may suffer.
I would have loved to have added this as a comment but I don't yet have 50 reputation so sorry for posting as a new answer!
How can I rename column in laravel using migration?
You need to create another migration file - and place it in there:
Run
Laravel 4: php artisan migrate:make rename_stnk_column
Laravel 5: php artisan make:migration rename_stnk_column
Then inside the new migration file place:
class RenameStnkColumn extends Migration
{
public function up()
{
Schema::table('stnk', function(Blueprint $table) {
$table->renameColumn('id', 'id_stnk');
});
}
public function down()
{
Schema::table('stnk', function(Blueprint $table) {
$table->renameColumn('id_stnk', 'id');
});
}
}
Sleep for milliseconds
The way to sleep your program in C++ is the Sleep(int)
method. The header file for it is #include "windows.h."
For example:
#include "stdafx.h"
#include "windows.h"
#include "iostream"
using namespace std;
int main()
{
int x = 6000;
Sleep(x);
cout << "6 seconds have passed" << endl;
return 0;
}
The time it sleeps is measured in milliseconds and has no limit.
Second = 1000 milliseconds
Minute = 60000 milliseconds
Hour = 3600000 milliseconds
'Source code does not match the bytecode' when debugging on a device
If you use Gradle, it is probably a problem with Gradle caches. (Reference). Alas, even if you run
gradle --refresh-dependencies
, it is not refreshing really all dependencies. Some rubbish remains. (Reference).
So, the most sure (but drastic and long) variant is to clear all inside from the [user]/.gradle/caches. Or to find your problem project there and clear only its caches.
How to Convert string "07:35" (HH:MM) to TimeSpan
You can convert the time using the following code.
TimeSpan _time = TimeSpan.Parse("07:35");
But if you want to get the current time of the day you can use the following code:
TimeSpan _CurrentTime = DateTime.Now.TimeOfDay;
The result will be:
03:54:35.7763461
With a object cantain the Hours, Minutes, Seconds, Ticks and etc.
FPDF error: Some data has already been output, can't send PDF
For fpdf to work properly, there cannot be any output at all beside what fpdf generates. For example, this will work:
<?php
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>
While this will not (note the leading space before the opening <?
tag)
<?php
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>
Also, this will not work either (the echo
will break it):
<?php
echo "About to create pdf";
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>
I'm not sure about the drupal side of things, but I know that absolutely zero non-fpdf output is a requirement for fpdf to work.
add ob_start ();
at the top and at the end add ob_end_flush();
<?php
ob_start();
require('fpdf.php');
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
ob_end_flush();
?>
give me an error as below:
FPDF error: Some data has already been output, can't send PDF
to over come this error:
go to fpdf.php
in that,goto line number 996
function Output($name='', $dest='')
after that make changes like this:
function Output($name='', $dest='') {
ob_clean();
Hi do you have a session header on the top of your page.
or any includes
If you have then try to add this codes on top pf your page it should works fine.
<?
while (ob_get_level())
ob_end_clean();
header("Content-Encoding: None", true);
?>
cheers :-)
In my case i had set:
ini_set('display_errors', 'on');
error_reporting(E_ALL | E_STRICT);
When i made the request to generate the report, some warnings were displayed in the browser (like the usage of deprecated functions).
Turning off
the display_errors
option, the report was generated successfully.
How to get an object's properties in JavaScript / jQuery?
Scanning object for first intance of a determinated prop:
var obj = {a:'Saludos',
b:{b_1:{b_1_1:'Como estas?',b_1_2:'Un gusto conocerte'}},
d:'Hasta luego'
}
function scan (element,list){
var res;
if (typeof(list) != 'undefined'){
if (typeof(list) == 'object'){
for(key in list){
if (typeof(res) == 'undefined'){
res = (key == element)?list[key]:scan(element,list[key]);
}
});
}
}
return res;
}
console.log(scan('a',obj));
When should I use double or single quotes in JavaScript?
I use single quotes most of the time, because when developing in PHP, single quoted-string are in no way altered, which is what I want. When I use
echo "$xyz";
In PHP, $xyz gets evaluated, which is not what I want. Therefore I always use '
instead of "
when it comes to web development. So I ensure at least string-consistency when it comes to PHP/JavaScript.
Unfortunately this can't be done in Java or Objective-C, where ''
stands for character and ""
stands for string. But this is another question.
How to know if docker is already logged in to a docker registry server
The docker cli credential scheme is unsurprisingly uncomplicated, just take a look:
cat ~/.docker/config.json
{
"auths": {
"dockerregistry.myregistry.com": {},
"https://index.docker.io/v1/": {}
This exists on Windows (use Get-Content ~\.docker\config.json
) and you can also poke around the credential tool which also lists the username ... and I think you can even retrieve the password
. "C:\Program Files\Docker\Docker\resources\bin\docker-credential-wincred.exe" list
{"https://index.docker.io/v1/":"kcd"}
PHP expects T_PAAMAYIM_NEKUDOTAYIM?
For me this happened within a class function.
In PHP 5.3 and above $this::$defaults
worked fine; when I swapped the code into a server that for whatever reason had a lower version number it threw this error.
The solution, in my case, was to use the keyword self
instead of $this
:
self::$defaults
works just fine.
How to convert C# nullable int to int
GetValueOrDefault()
retrieves the value of the object. If it is null, it returns the default value of int , which is 0.
Example:
v2= v1.GetValueOrDefault();
Clearing input in vuejs form
This solution is only for components
If we toggle(show/hide) components using booleans then data is also removed.
No need to clean the form fields.
I usually make components and initialize them using booleans.
e.g.
<template>
<button @click="show_create_form = true">Add New Record</button
<create-form v-if="show_create_form" />
</template>
<script>
...
data(){
return{
show_create_form:false //making it false by default
}
},
methods:{
submitForm(){
//...
this.axios.post('/submit-form-url',data,config)
.then((response) => {
this.show_create_form= false; //hide it again after success.
//if you now click on add new record button then it will show you empty form
}).catch((error) => {
//
})
}
}
...
</script>
When use clicks on edit button then this boolean becomes true and after successful submit I change it to false again.
Toggle visibility property of div
To clean this up a little bit and maintain a single line of code (like you would with a toggle()
), you can use a ternary operator so your code winds up looking like this (also using jQuery):
$('#video-over').css('visibility', $('#video-over').css('visibility') == 'hidden' ? 'visible' : 'hidden');
Creating multiline strings in JavaScript
Easiest way to make multiline strings in Javascrips is with the use of backticks ( `` ). This allows you to create multiline strings in which you can insert variables with ${variableName}
.
Example:
_x000D_
_x000D_
let name = 'Willem'; _x000D_
let age = 26;_x000D_
_x000D_
let multilineString = `_x000D_
my name is: ${name}_x000D_
_x000D_
my age is: ${age}_x000D_
`;_x000D_
_x000D_
console.log(multilineString);
_x000D_
_x000D_
_x000D_
compatibility :
- It was introduces in
ES6
//es2015
- It is now natively supported by all major browser vendors (except internet explorer)
Check exact compatibility in Mozilla docs here
Trying to use INNER JOIN and GROUP BY SQL with SUM Function, Not Working
Two ways to do it...
GROUP BY
SELECT RES.[CUSTOMER ID], RES,NAME, SUM(INV.AMOUNT) AS [TOTAL AMOUNT]
FROM RES_DATA RES
JOIN INV_DATA INV ON RES.[CUSTOMER ID] INV.[CUSTOMER ID]
GROUP BY RES.[CUSTOMER ID], RES,NAME
OVER
SELECT RES.[CUSTOMER ID], RES,NAME,
SUM(INV.AMOUNT) OVER (PARTITION RES.[CUSTOMER ID]) AS [TOTAL AMOUNT]
FROM RES_DATA RES
JOIN INV_DATA INV ON RES.[CUSTOMER ID] INV.[CUSTOMER ID]
Deserializing JSON Object Array with Json.net
Using the accepted answer you have to access each record by using Customers[i].customer
, and you need an extra CustomerJson
class, which is a little annoying. If you don't want to do that, you can use the following:
public class CustomerList
{
[JsonConverter(typeof(MyListConverter))]
public List<Customer> customer { get; set; }
}
Note that I'm using a List<>
, not an Array. Now create the following class:
class MyListConverter : JsonConverter
{
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var token = JToken.Load(reader);
var list = Activator.CreateInstance(objectType) as System.Collections.IList;
var itemType = objectType.GenericTypeArguments[0];
foreach (var child in token.Values())
{
var childToken = child.Children().First();
var newObject = Activator.CreateInstance(itemType);
serializer.Populate(childToken.CreateReader(), newObject);
list.Add(newObject);
}
return list;
}
public override bool CanConvert(Type objectType)
{
return objectType.IsGenericType && (objectType.GetGenericTypeDefinition() == typeof(List<>));
}
public override bool CanWrite => false;
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) => throw new NotImplementedException();
}
How to add multiple jar files in classpath in linux
Say you have multiple jar files a.jar,b.jar and c.jar. To add them to classpath while compiling you need to do
$javac -cp .:a.jar:b.jar:c.jar HelloWorld.java
To run do
$java -cp .:a.jar:b.jar:c.jar HelloWorld
Build Error - missing required architecture i386 in file
I just wanted to mention that in XCode if you go to "Edit Project Settings"
and find "Search Paths" There is a field for "Framework Search Paths". Updating this should fix the problem, without having to hack the project file!
Cheers!
Jesse
How to calculate number of days between two given dates?
Here are three ways to go with this problem :
from datetime import datetime
Now = datetime.now()
StartDate = datetime.strptime(str(Now.year) +'-01-01', '%Y-%m-%d')
NumberOfDays = (Now - StartDate)
print(NumberOfDays.days) # Starts at 0
print(datetime.now().timetuple().tm_yday) # Starts at 1
print(Now.strftime('%j')) # Starts at 1
jQuery ajax success error
You did not provide your validate.php
code so I'm confused. You have to pass the data in JSON Format when when mail is success.
You can use json_encode(); PHP function for that.
Add json_encdoe
in validate.php in last
mail($to, $subject, $message, $headers);
echo json_encode(array('success'=>'true'));
JS Code
success: function(data){
if(data.success == true){
alert('success');
}
Hope it works
Remove a HTML tag but keep the innerHtml
How about this?
$("b").insertAdjacentHTML("afterend",$("b").innerHTML);
$("b").parentNode.removeChild($("b"));
The first line copies the HTML contents of the b
tag to the location directly after the b
tag, and then the second line removes the b
tag from the DOM, leaving only its copied contents.
I normally wrap this into a function to make it easier to use:
function removeElementTags(element) {
element.insertAdjacentHTML("afterend",element.innerHTML);
element.parentNode.removeChild(element);
}
All of the code is actually pure Javascript, the only JQuery being used is that to select the element to target (the b
tag in the first example). The function is just pure JS :D
Also look at:
How can I change Eclipse theme?
In the eclipse Version: 2019-09 R (4.13.0) on windows
Go to Window > preferences > Appearance
Select the required theme for dark theme to choose Dark and click on Ok.
Convert PDF to image with high resolution
The following python script will work on any Mac (Snow Leopard and upward). It can be used on the command line with successive PDF files as arguments, or you can put in into a Run Shell Script action in Automator, and make a Service (Quick Action in Mojave).
You can set the resolution of the output image in the script.
The script and a Quick Action can be downloaded from github.
#!/usr/bin/python
# coding: utf-8
import os, sys
import Quartz as Quartz
from LaunchServices import (kUTTypeJPEG, kUTTypeTIFF, kUTTypePNG, kCFAllocatorDefault)
resolution = 300.0 #dpi
scale = resolution/72.0
cs = Quartz.CGColorSpaceCreateWithName(Quartz.kCGColorSpaceSRGB)
whiteColor = Quartz.CGColorCreate(cs, (1, 1, 1, 1))
# Options: kCGImageAlphaNoneSkipLast (no trans), kCGImageAlphaPremultipliedLast
transparency = Quartz.kCGImageAlphaNoneSkipLast
#Save image to file
def writeImage (image, url, type, options):
destination = Quartz.CGImageDestinationCreateWithURL(url, type, 1, None)
Quartz.CGImageDestinationAddImage(destination, image, options)
Quartz.CGImageDestinationFinalize(destination)
return
def getFilename(filepath):
i=0
newName = filepath
while os.path.exists(newName):
i += 1
newName = filepath + " %02d"%i
return newName
if __name__ == '__main__':
for filename in sys.argv[1:]:
pdf = Quartz.CGPDFDocumentCreateWithProvider(Quartz.CGDataProviderCreateWithFilename(filename))
numPages = Quartz.CGPDFDocumentGetNumberOfPages(pdf)
shortName = os.path.splitext(filename)[0]
prefix = os.path.splitext(os.path.basename(filename))[0]
folderName = getFilename(shortName)
try:
os.mkdir(folderName)
except:
print "Can't create directory '%s'"%(folderName)
sys.exit()
# For each page, create a file
for i in range (1, numPages+1):
page = Quartz.CGPDFDocumentGetPage(pdf, i)
if page:
#Get mediabox
mediaBox = Quartz.CGPDFPageGetBoxRect(page, Quartz.kCGPDFMediaBox)
x = Quartz.CGRectGetWidth(mediaBox)
y = Quartz.CGRectGetHeight(mediaBox)
x *= scale
y *= scale
r = Quartz.CGRectMake(0,0,x, y)
# Create a Bitmap Context, draw a white background and add the PDF
writeContext = Quartz.CGBitmapContextCreate(None, int(x), int(y), 8, 0, cs, transparency)
Quartz.CGContextSaveGState (writeContext)
Quartz.CGContextScaleCTM(writeContext, scale,scale)
Quartz.CGContextSetFillColorWithColor(writeContext, whiteColor)
Quartz.CGContextFillRect(writeContext, r)
Quartz.CGContextDrawPDFPage(writeContext, page)
Quartz.CGContextRestoreGState(writeContext)
# Convert to an "Image"
image = Quartz.CGBitmapContextCreateImage(writeContext)
# Create unique filename per page
outFile = folderName +"/" + prefix + " %03d.png"%i
url = Quartz.CFURLCreateFromFileSystemRepresentation(kCFAllocatorDefault, outFile, len(outFile), False)
# kUTTypeJPEG, kUTTypeTIFF, kUTTypePNG
type = kUTTypePNG
# See the full range of image properties on Apple's developer pages.
options = {
Quartz.kCGImagePropertyDPIHeight: resolution,
Quartz.kCGImagePropertyDPIWidth: resolution
}
writeImage (image, url, type, options)
del page
Convert canvas to PDF
So for today, jspdf-1.5.3.
To answer the question of having the pdf file page exactly same as the canvas. After many tries of different combinations, I figured you gotta do something like this.
We first need to set the height and width for the output pdf file with correct orientation, otherwise the sides might be cut off. Then we get the dimensions from the 'pdf' file itself, if you tried to use the canvas's dimensions, the sides might be cut off again. I am not sure why that happens, my best guess is the jsPDF convert the dimensions in other units in the library.
// Download button
$("#download-image").on('click', function () {
let width = __CANVAS.width;
let height = __CANVAS.height;
//set the orientation
if(width > height){
pdf = new jsPDF('l', 'px', [width, height]);
}
else{
pdf = new jsPDF('p', 'px', [height, width]);
}
//then we get the dimensions from the 'pdf' file itself
width = pdf.internal.pageSize.getWidth();
height = pdf.internal.pageSize.getHeight();
pdf.addImage(__CANVAS, 'PNG', 0, 0,width,height);
pdf.save("download.pdf");
});
Learnt about switching orientations from here:
https://github.com/MrRio/jsPDF/issues/476
Convert DataTable to CSV stream
I've used the following code, pillaged from someone's blog (pls forgive lack of citation). It takes care of quotations, newline and comma in a reasonably elegant way by quoting out each field value.
/// <summary>
/// Converts the passed in data table to a CSV-style string.
/// </summary>
/// <param name="table">Table to convert</param>
/// <returns>Resulting CSV-style string</returns>
public static string ToCSV(this DataTable table)
{
return ToCSV(table, ",", true);
}
/// <summary>
/// Converts the passed in data table to a CSV-style string.
/// </summary>
/// <param name="table">Table to convert</param>
/// <param name="includeHeader">true - include headers<br/>
/// false - do not include header column</param>
/// <returns>Resulting CSV-style string</returns>
public static string ToCSV(this DataTable table, bool includeHeader)
{
return ToCSV(table, ",", includeHeader);
}
/// <summary>
/// Converts the passed in data table to a CSV-style string.
/// </summary>
/// <param name="table">Table to convert</param>
/// <param name="includeHeader">true - include headers<br/>
/// false - do not include header column</param>
/// <returns>Resulting CSV-style string</returns>
public static string ToCSV(this DataTable table, string delimiter, bool includeHeader)
{
var result = new StringBuilder();
if (includeHeader)
{
foreach (DataColumn column in table.Columns)
{
result.Append(column.ColumnName);
result.Append(delimiter);
}
result.Remove(--result.Length, 0);
result.Append(Environment.NewLine);
}
foreach (DataRow row in table.Rows)
{
foreach (object item in row.ItemArray)
{
if (item is DBNull)
result.Append(delimiter);
else
{
string itemAsString = item.ToString();
// Double up all embedded double quotes
itemAsString = itemAsString.Replace("\"", "\"\"");
// To keep things simple, always delimit with double-quotes
// so we don't have to determine in which cases they're necessary
// and which cases they're not.
itemAsString = "\"" + itemAsString + "\"";
result.Append(itemAsString + delimiter);
}
}
result.Remove(--result.Length, 0);
result.Append(Environment.NewLine);
}
return result.ToString();
}
Semaphore vs. Monitors - what's the difference?
When a semaphore is used to guard a critical region, there is no direct relationship between the semaphore and the data being protected. This is part of the reason why semaphores may be dispersed around the code, and why it is easy to forget to call wait or notify, in which case the result will be, respectively, to violate mutual exclusion or to lock the resource permanently.
In contrast, niehter of these bad things can happen with a monitor. A monitor is tired directly to the data (it encapsulates the data) and, because the monitor operations are atomic actions, it is impossible to write code that can access the data without calling the entry protocol. The exit protocol is called automatically when the monitor operation is completed.
A monitor has a built-in mechanism for condition synchronisation in the form of condition variable before proceeding. If the condition is not satisfied, the process has to wait until it is notified of a change in the condition. When a process is waiting for condition synchronisation, the monitor implementation takes care of the mutual exclusion issue, and allows another process to gain access to the monitor.
Taken from The Open University M362 Unit 3 "Interacting process" course material.
Could someone explain this for me - for (int i = 0; i < 8; i++)
it's the same as think the next:
"starting with i = 0, while i is less than 8, and adding one to i at the end of the parenthesis, do the instructions between brackets"
It's also the same as:
while( i < 8 )
{
// instrucctions like:
Console.WriteLine(i);
i++;
}
the For sentences is a basis of coding, and it's as useful as necessary its understanding.
It's the way to repeat n-times the same instrucction, or browse ( or do something with each element) an array
Is it possible to pull just one file in Git?
Yes, here is the process:
# Navigate to a directory and initiate a local repository
git init
# Add remote repository to be tracked for changes:
git remote add origin https://github.com/username/repository_name.git
# Track all changes made on above remote repository
# This will show files on remote repository not available on local repository
git fetch
# Add file present in staging area for checkout
git check origin/master -m /path/to/file
# NOTE: /path/to/file is a relative path from repository_name
git add /path/to/file
# Verify track of file(s) being committed to local repository
git status
# Commit to local repository
git commit -m "commit message"
# You may perform a final check of the staging area again with git status
git push rejected
First, attempt to pull from the same refspec that you are trying to push to.
If this does not work, you can force a git push
by using git push -f <repo> <refspec>
, but use caution: this method can cause references to be deleted on the remote repository.
Check if date is in the past Javascript
To make the answer more re-usable for things other than just the datepicker change function you can create a prototype to handle this for you.
// safety check to see if the prototype name is already defined
Function.prototype.method = function (name, func) {
if (!this.prototype[name]) {
this.prototype[name] = func;
return this;
}
};
Date.method('inPast', function () {
return this < new Date($.now());// the $.now() requires jQuery
});
// including this prototype as using in example
Date.method('addDays', function (days) {
var date = new Date(this);
date.setDate(date.getDate() + (days));
return date;
});
If you dont like the safety check you can use the conventional way to define prototypes:
Date.prototype.inPast = function(){
return this < new Date($.now());// the $.now() requires jQuery
}
Example Usage
var dt = new Date($.now());
var yesterday = dt.addDays(-1);
var tomorrow = dt.addDays(1);
console.log('Yesterday: ' + yesterday.inPast());
console.log('Tomorrow: ' + tomorrow.inPast());
Pointer to a string in C?
The same notation is used for pointing at a single character or the first character of a null-terminated string:
char c = 'Z';
char a[] = "Hello world";
char *ptr1 = &c;
char *ptr2 = a; // Points to the 'H' of "Hello world"
char *ptr3 = &a[0]; // Also points to the 'H' of "Hello world"
char *ptr4 = &a[6]; // Points to the 'w' of "world"
char *ptr5 = a + 6; // Also points to the 'w' of "world"
The values in ptr2
and ptr3
are the same; so are the values in ptr4
and ptr5
. If you're going to treat some data as a string, it is important to make sure it is null terminated, and that you know how much space there is for you to use. Many problems are caused by not understanding what space is available and not knowing whether the string was properly null terminated.
Note that all the pointers above can be dereferenced as if they were an array:
*ptr1 == 'Z'
ptr1[0] == 'Z'
*ptr2 == 'H'
ptr2[0] == 'H'
ptr2[4] == 'o'
*ptr4 == 'w'
ptr4[0] == 'w'
ptr4[4] == 'd'
ptr5[0] == ptr3[6]
*(ptr5+0) == *(ptr3+6)
Late addition to question
What does char (*ptr)[N];
represent?
This is a more complex beastie altogether. It is a pointer to an array of N
characters. The type is quite different; the way it is used is quite different; the size of the object pointed to is quite different.
char (*ptr)[12] = &a;
(*ptr)[0] == 'H'
(*ptr)[6] == 'w'
*(*ptr + 6) == 'w'
Note that ptr + 1
points to undefined territory, but points 'one array of 12 bytes' beyond the start of a
. Given a slightly different scenario:
char b[3][12] = { "Hello world", "Farewell", "Au revoir" };
char (*pb)[12] = &b[0];
Now:
(*(pb+0))[0] == 'H'
(*(pb+1))[0] == 'F'
(*(pb+2))[5] == 'v'
You probably won't come across pointers to arrays except by accident for quite some time; I've used them a few times in the last 25 years, but so few that I can count the occasions on the fingers of one hand (and several of those have been answering questions on Stack Overflow). Beyond knowing that they exist, that they are the result of taking the address of an array, and that you probably didn't want it, you don't really need to know more about pointers to arrays.
Measure the time it takes to execute a t-sql query
even better, this will measure the average of n iterations of your query! Great for a more accurate reading.
declare @tTOTAL int = 0
declare @i integer = 0
declare @itrs integer = 100
while @i < @itrs
begin
declare @t0 datetime = GETDATE()
--your query here
declare @t1 datetime = GETDATE()
set @tTotal = @tTotal + DATEDIFF(MICROSECOND,@t0,@t1)
set @i = @i + 1
end
select @tTotal/@itrs
How to use a dot "." to access members of dictionary?
Not a direct answer to the OP's question, but inspired by and perhaps useful for some.. I've created an object-based solution using the internal __dict__
(In no way optimized code)
payload = {
"name": "John",
"location": {
"lat": 53.12312312,
"long": 43.21345112
},
"numbers": [
{
"role": "home",
"number": "070-12345678"
},
{
"role": "office",
"number": "070-12345679"
}
]
}
class Map(object):
"""
Dot style access to object members, access raw values
with an underscore e.g.
class Foo(Map):
def foo(self):
return self.get('foo') + 'bar'
obj = Foo(**{'foo': 'foo'})
obj.foo => 'foobar'
obj._foo => 'foo'
"""
def __init__(self, *args, **kwargs):
for arg in args:
if isinstance(arg, dict):
for k, v in arg.iteritems():
self.__dict__[k] = v
self.__dict__['_' + k] = v
if kwargs:
for k, v in kwargs.iteritems():
self.__dict__[k] = v
self.__dict__['_' + k] = v
def __getattribute__(self, attr):
if hasattr(self, 'get_' + attr):
return object.__getattribute__(self, 'get_' + attr)()
else:
return object.__getattribute__(self, attr)
def get(self, key):
try:
return self.__dict__.get('get_' + key)()
except (AttributeError, TypeError):
return self.__dict__.get(key)
def __repr__(self):
return u"<{name} object>".format(
name=self.__class__.__name__
)
class Number(Map):
def get_role(self):
return self.get('role')
def get_number(self):
return self.get('number')
class Location(Map):
def get_latitude(self):
return self.get('lat') + 1
def get_longitude(self):
return self.get('long') + 1
class Item(Map):
def get_name(self):
return self.get('name') + " Doe"
def get_location(self):
return Location(**self.get('location'))
def get_numbers(self):
return [Number(**n) for n in self.get('numbers')]
# Tests
obj = Item({'foo': 'bar'}, **payload)
assert type(obj) == Item
assert obj._name == "John"
assert obj.name == "John Doe"
assert type(obj.location) == Location
assert obj.location._lat == 53.12312312
assert obj.location._long == 43.21345112
assert obj.location.latitude == 54.12312312
assert obj.location.longitude == 44.21345112
for n in obj.numbers:
assert type(n) == Number
if n.role == 'home':
assert n.number == "070-12345678"
if n.role == 'office':
assert n.number == "070-12345679"
Why doesn't Java offer operator overloading?
There are a lot of posts complaining about operator overloading.
I felt I had to clarify the "operator overloading" concepts, offering an alternative viewpoint on this concept.
#Code obfuscating?
This argument is a fallacy.
##Obfuscating is possible in all languages...
It is as easy to obfuscate code in C or Java through functions/methods as it is in C++ through operator overloads:
// C++
T operator + (const T & a, const T & b) // add ?
{
T c ;
c.value = a.value - b.value ; // subtract !!!
return c ;
}
// Java
static T add (T a, T b) // add ?
{
T c = new T() ;
c.value = a.value - b.value ; // subtract !!!
return c ;
}
/* C */
T add (T a, T b) /* add ? */
{
T c ;
c.value = a.value - b.value ; /* subtract !!! */
return c ;
}
##...Even in Java's standard interfaces
For another example, let's see the Cloneable
interface in Java:
You are supposed to clone the object implementing this interface. But you could lie. And create a different object. In fact, this interface is so weak you could return another type of object altogether, just for the fun of it:
class MySincereHandShake implements Cloneable
{
public Object clone()
{
return new MyVengefulKickInYourHead() ;
}
}
As the Cloneable
interface can be abused/obfuscated, should it be banned on the same grounds C++ operator overloading is supposed to be?
We could overload the toString()
method of a MyComplexNumber
class to have it return the stringified hour of the day. Should the toString()
overloading be banned, too? We could sabotage MyComplexNumber.equals
to have it return a random value, modify the operands... etc. etc. etc..
In Java, as in C++, or whatever language, the programmer must respect a minimum of semantics when writing code. This means implementing a add
function that adds, and Cloneable
implementation method that clones, and a ++
operator than increments.
#What's obfuscating anyway?
Now that we know that code can be sabotaged even through the pristine Java methods, we can ask ourselves about the real use of operator overloading in C++?
##Clear and natural notation: methods vs. operator overloading?
We'll compare below, for different cases, the "same" code in Java and C++, to have an idea of which kind of coding style is clearer.
###Natural comparisons:
// C++ comparison for built-ins and user-defined types
bool isEqual = A == B ;
bool isNotEqual = A != B ;
bool isLesser = A < B ;
bool isLesserOrEqual = A <= B ;
// Java comparison for user-defined types
boolean isEqual = A.equals(B) ;
boolean isNotEqual = ! A.equals(B) ;
boolean isLesser = A.comparesTo(B) < 0 ;
boolean isLesserOrEqual = A.comparesTo(B) <= 0 ;
Please note that A and B could be of any type in C++, as long as the operator overloads are provided. In Java, when A and B are not primitives, the code can become very confusing, even for primitive-like objects (BigInteger, etc.)...
###Natural array/container accessors and subscripting:
// C++ container accessors, more natural
value = myArray[25] ; // subscript operator
value = myVector[25] ; // subscript operator
value = myString[25] ; // subscript operator
value = myMap["25"] ; // subscript operator
myArray[25] = value ; // subscript operator
myVector[25] = value ; // subscript operator
myString[25] = value ; // subscript operator
myMap["25"] = value ; // subscript operator
// Java container accessors, each one has its special notation
value = myArray[25] ; // subscript operator
value = myVector.get(25) ; // method get
value = myString.charAt(25) ; // method charAt
value = myMap.get("25") ; // method get
myArray[25] = value ; // subscript operator
myVector.set(25, value) ; // method set
myMap.put("25", value) ; // method put
In Java, we see that for each container to do the same thing (access its content through an index or identifier), we have a different way to do it, which is confusing.
In C++, each container uses the same way to access its content, thanks to operator overloading.
###Natural advanced types manipulation
The examples below use a Matrix
object, found using the first links found on Google for "Java Matrix object" and "C++ Matrix object":
// C++ YMatrix matrix implementation on CodeProject
// http://www.codeproject.com/KB/architecture/ymatrix.aspx
// A, B, C, D, E, F are Matrix objects;
E = A * (B / 2) ;
E += (A - B) * (C + D) ;
F = E ; // deep copy of the matrix
// Java JAMA matrix implementation (seriously...)
// http://math.nist.gov/javanumerics/jama/doc/
// A, B, C, D, E, F are Matrix objects;
E = A.times(B.times(0.5)) ;
E.plusEquals(A.minus(B).times(C.plus(D))) ;
F = E.copy() ; // deep copy of the matrix
And this is not limited to matrices. The BigInteger
and BigDecimal
classes of Java suffer from the same confusing verbosity, whereas their equivalents in C++ are as clear as built-in types.
###Natural iterators:
// C++ Random Access iterators
++it ; // move to the next item
--it ; // move to the previous item
it += 5 ; // move to the next 5th item (random access)
value = *it ; // gets the value of the current item
*it = 3.1415 ; // sets the value 3.1415 to the current item
(*it).foo() ; // call method foo() of the current item
// Java ListIterator<E> "bi-directional" iterators
value = it.next() ; // move to the next item & return the value
value = it.previous() ; // move to the previous item & return the value
it.set(3.1415) ; // sets the value 3.1415 to the current item
###Natural functors:
// C++ Functors
myFunctorObject("Hello World", 42) ;
// Java Functors ???
myFunctorObject.execute("Hello World", 42) ;
###Text concatenation:
// C++ stream handling (with the << operator)
stringStream << "Hello " << 25 << " World" ;
fileStream << "Hello " << 25 << " World" ;
outputStream << "Hello " << 25 << " World" ;
networkStream << "Hello " << 25 << " World" ;
anythingThatOverloadsShiftOperator << "Hello " << 25 << " World" ;
// Java concatenation
myStringBuffer.append("Hello ").append(25).append(" World") ;
Ok, in Java you can use MyString = "Hello " + 25 + " World" ;
too... But, wait a second: This is operator overloading, isn't it? Isn't it cheating???
:-D
##Generic code?
The same generic code modifying operands should be usable both for built-ins/primitives (which have no interfaces in Java), standard objects (which could not have the right interface), and user-defined objects.
For example, calculating the average value of two values of arbitrary types:
// C++ primitive/advanced types
template<typename T>
T getAverage(const T & p_lhs, const T & p_rhs)
{
return (p_lhs + p_rhs) / 2 ;
}
int intValue = getAverage(25, 42) ;
double doubleValue = getAverage(25.25, 42.42) ;
complex complexValue = getAverage(cA, cB) ; // cA, cB are complex
Matrix matrixValue = getAverage(mA, mB) ; // mA, mB are Matrix
// Java primitive/advanced types
// It won't really work in Java, even with generics. Sorry.
#Discussing operator overloading
Now that we have seen fair comparisons between C++ code using operator overloading, and the same code in Java, we can now discuss "operator overloading" as a concept.
##Operator overloading existed since before computers
Even outside of computer science, there is operator overloading: For example, in mathematics, operators like +
, -
, *
, etc. are overloaded.
Indeed, the signification of +
, -
, *
, etc. changes depending on the types of the operands (numerics, vectors, quantum wave functions, matrices, etc.).
Most of us, as part of our science courses, learned multiple significations for operators, depending on the types of the operands. Did we find them confusing, them?
##Operator overloading depends on its operands
This is the most important part of operator overloading: Like in mathematics, or in physics, the operation depends on its operands' types.
So, know the type of the operand, and you will know the effect of the operation.
##Even C and Java have (hard-coded) operator overloading
In C, the real behavior of an operator will change according to its operands. For example, adding two integers is different than adding two doubles, or even one integer and one double. There is even the whole pointer arithmetic domain (without casting, you can add to a pointer an integer, but you cannot add two pointers...).
In Java, there is no pointer arithmetic, but someone still found string concatenation without the +
operator would be ridiculous enough to justify an exception in the "operator overloading is evil" creed.
It's just that you, as a C (for historical reasons) or Java (for personal reasons, see below) coder, you can't provide your own.
##In C++, operator overloading is not optional...
In C++, operator overloading for built-in types is not possible (and this is a good thing), but user-defined types can have user-defined operator overloads.
As already said earlier, in C++, and to the contrary to Java, user-types are not considered second-class citizens of the language, when compared to built-in types. So, if built-in types have operators, user types should be able to have them, too.
The truth is that, like the toString()
, clone()
, equals()
methods are for Java (i.e. quasi-standard-like), C++ operator overloading is so much part of C++ that it becomes as natural as the original C operators, or the before mentioned Java methods.
Combined with template programming, operator overloading becomes a well known design pattern. In fact, you cannot go very far in STL without using overloaded operators, and overloading operators for your own class.
##...but it should not be abused
Operator overloading should strive to respect the semantics of the operator. Do not subtract in a +
operator (as in "do not subtract in a add
function", or "return crap in a clone
method").
Cast overloading can be very dangerous because they can lead to ambiguities. So they should really be reserved for well defined cases. As for &&
and ||
, do not ever overload them unless you really know what you're doing, as you'll lose the the short circuit evaluation that the native operators &&
and ||
enjoy.
#So... Ok... Then why it is not possible in Java?
Because James Gosling said so:
I left out operator overloading as a fairly personal choice because I had seen too many people abuse it in C++.
James Gosling. Source: http://www.gotw.ca/publications/c_family_interview.htm
Please compare Gosling's text above with Stroustrup's below:
Many C++ design decisions have their roots in my dislike for forcing people to do things in some particular way [...] Often, I was tempted to outlaw a feature I personally disliked, I refrained from doing so because I did not think I had the right to force my views on others.
Bjarne Stroustrup. Source: The Design and Evolution of C++ (1.3 General Background)
##Would operator overloading benefit Java?
Some objects would greatly benefit from operator overloading (concrete or numerical types, like BigDecimal, complex numbers, matrices, containers, iterators, comparators, parsers etc.).
In C++, you can profit from this benefit because of Stroustrup's humility. In Java, you're simply screwed because of Gosling's personal choice.
##Could it be added to Java?
The reasons for not adding operator overloading now in Java could be a mix of internal politics, allergy to the feature, distrust of developers (you know, the saboteur ones that seem to haunt Java teams...), compatibility with the previous JVMs, time to write a correct specification, etc..
So don't hold your breath waiting for this feature...
##But they do it in C#!!!
Yeah...
While this is far from being the only difference between the two languages, this one never fails to amuse me.
Apparently, the C# folks, with their "every primitive is a struct
, and a struct
derives from Object", got it right at first try.
##And they do it in other languages!!!
Despite all the FUD against used defined operator overloading, the following languages support it: Kotlin, Scala, Dart, Python, F#, C#, D, Algol 68, Smalltalk, Groovy, Perl 6, C++, Ruby, Haskell, MATLAB, Eiffel, Lua, Clojure, Fortran 90, Swift, Ada, Delphi 2005...
So many languages, with so many different (and sometimes opposing) philosophies, and yet they all agree on that point.
Food for thought...
How do I install Python 3 on an AWS EC2 instance?
As @NickT said, there's no python3[4-6] in the default yum repos in Amazon Linux 2, as of today it uses 3.7 and looking at all answers here we can say it will be changed over time.
I was looking for python3.6 on Amazon Linux 2 but amazon-linux-extras
shows a lot of options but no python at all. in fact, you can try to find the version you know in epel
repo:
sudo amazon-linux-extras install epel
yum search python | grep "^python3..x8"
python34.x86_64 : Version 3 of the Python programming language aka Python 3000
python36.x86_64 : Interpreter of the Python programming language
Retaining file permissions with Git
In pre-commit/post-checkout an option would be to use "mtree" (FreeBSD), or "fmtree" (Ubuntu) utility which "compares a file hierarchy against a specification, creates a specification for a file hierarchy, or modifies a specification."
The default set are flags, gid, link, mode, nlink, size, time, type, and uid. This can be fitted to the specific purpose with -k switch.
How to uninstall mini conda? python
To update @Sunil answer: Under Windows, Miniconda has a regular uninstaller. Go to the menu "Settings/Apps/Apps&Features", or click the Start button, type "uninstall", then click on "Add or Remove Programs" and finally on the Miniconda uninstaller.
Avoid dropdown menu close on click inside
You could simply execute event.stopPropagation
on click event of the links themselves.
Something like this.
$(".dropdown-menu a").click((event) => {
event.stopPropagation()
let url = event.target.href
//Do something with the url or any other logic you wish
})
Edit: If someone saw this answer and is using react, it will not work.
React handle the javascript events differently and by the time your react event handler is being called, the event has already been fired and propagated. To overcome that you should attach the event manually like that
handleMenuClick(event) {
event.stopPropagation()
let menu_item = event.target
//implement your logic here.
}
componentDidMount() {
document.getElementsByClassName("dropdown-menu")[0].addEventListener(
"click", this.handleMenuClick.bind(this), false)
}
}
Best way to strip punctuation from a string
For the convenience of usage, I sum up the note of striping punctuation from a string in both Python 2 and Python 3. Please refer to other answers for the detailed description.
Python 2
import string
s = "string. With. Punctuation?"
table = string.maketrans("","")
new_s = s.translate(table, string.punctuation) # Output: string without punctuation
Python 3
import string
s = "string. With. Punctuation?"
table = str.maketrans(dict.fromkeys(string.punctuation)) # OR {key: None for key in string.punctuation}
new_s = s.translate(table) # Output: string without punctuation
How to put an image in div with CSS?
With Javascript/Jquery:
- load image with hidden
img
- when image has been loaded, get width and height
- dynamically create a
div
and set width, height and background
remove the original img
$(document).ready(function() {
var image = $("<img>");
var div = $("<div>")
image.load(function() {
div.css({
"width": this.width,
"height": this.height,
"background-image": "url(" + this.src + ")"
});
$("#container").append(div);
});
image.attr("src", "test0.png");
});